// http 拦截器
import axios from 'axios'
import router from '@/router'
import { clearAllStore, getStore } from '@/utils/util.js'
import { ElMessage } from 'element-plus'


// api方法白名单
let whiteApi = [
  '/api/login', '/api/register'
]

const http = axios.create({
  timeout: 5000
})

http.interceptors.request.use(
  config => {
    if (whiteApi.indexOf(config.url) === -1) {
      config.headers['token'] = getStore('token') ?? ''
    }
    config.method = config.method.toUpperCase() || 'GET'
    config.method = config.method.toUpperCase() || 'GET'
    if (config.params && config.params?.pageNum) {
      config.params.pageNo = config.params.pageNum
      delete config.params.pageNum
    }
    if (config.method === 'post' || config.method === 'put') {
      config.params = JSON.stringify(config.params)
    }
    return config
  },
  err => {
    // app.config.globalProperties.$loading.hideLoading();
    return Promise.reject(err)
  }
)

http.interceptors.response.use(
  response => {
    switch (response.data.code) {
      case 200:
        return response.data
      case 600:
        ElMessage.error({
          message: response.data.msg,
          duration: 1500
        })
        return response.data
      default:
        return response.data
    }
  },
  error => {
    switch (error.response.data.code) {
      case 202:
        clearAllStore()
        router.push('/login')
        return Promise.reject(error.response.data.data)
      case 403:
        return Promise.reject(error.response.data.data)
      // return error.response
      default:
        ElMessage.error({
          message: error.response.data.msg,
          duration: 1500
        })
        clearAllStore()
        router.push('/login')
        return Promise.reject(error.response.data.data)
    }
  }
)

export default http
